﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using WebSocket4Net;
using Microsoft.ClearScript.JavaScript;
using Microsoft.ClearScript.V8;

namespace ICUConsole
{
    class Program
    {
        const string host = "wss://cn.starlight.cool:16188";
        static WebSocket webSocket = new WebSocket(host);
        static void Main(string[] args)
        {
            V8ScriptEngine engine = new V8ScriptEngine();
            engine.AddHostType("icu", typeof(Program));
            engine.AddHostType("file", typeof(File));
            engine.AddHostType("console", typeof(Console));
            engine.AddHostObject("ws", webSocket);
            webSocket.Closed += (object sender, EventArgs e) =>
              {
                  Console.ForegroundColor = ConsoleColor.Red;
                  Console.WriteLine("Connection closed.type 'y' to restart...");
                  Console.ForegroundColor = ConsoleColor.Gray;
                  if (Console.ReadKey().Key == ConsoleKey.Y)
                  {
                      webSocket = new WebSocket(host);
                      webSocket.Open();
                  }
                  else
                  {
                      return;
                  }
              };
            webSocket.Error += (object sender, SuperSocket.ClientEngine.ErrorEventArgs e) =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Exception);
                Console.ForegroundColor = ConsoleColor.Gray;
            };
            webSocket.MessageReceived += (object sender, MessageReceivedEventArgs e) =>
              {
                  if (e.Message.StartsWith("Error\n"))
                  {
                      Console.ForegroundColor = ConsoleColor.Red;
                      ICU.Errors errors = (ICU.Errors)Convert.ToInt32(e.Message.Split('\n')[1]);
                      Console.WriteLine("Error: {0}", errors.GetType().GetEnumName(errors));
                      Console.ForegroundColor = ConsoleColor.Gray;
                  }
                  else
                  {
                      Console.ForegroundColor = ConsoleColor.Blue;
                      Console.WriteLine(e.Message);
                      Console.ForegroundColor = ConsoleColor.Gray;
                  }
              };
            webSocket.DataReceived += (object sender, DataReceivedEventArgs e) =>
              {
                  Console.ForegroundColor = ConsoleColor.Green;
                  int p;
                  for (p = 0; File.Exists(p.ToString()); p++) { }
                  Console.WriteLine("Data received. stored at {0}",p);
                  File.WriteAllBytes(p.ToString(), e.Data);
                  Console.ForegroundColor = ConsoleColor.Gray;
              };
            webSocket.Open();
            while (true)
            {
                try
                {
                    string msg = Console.ReadLine();
                    if(!msg.StartsWith(' '))
                    {
                        webSocket.Send(msg.Replace("\\n", "\n"));
                    }
                    else
                    {
                        string[] cmd = msg.Split(' ')[1..];
                        switch (cmd[0])
                        {
                            case "msg":
                                Console.WriteLine(new JObject { { "msg", cmd[1] }, { "target", Convert.ToInt64(cmd[2][1..]) }, { "isGroup", cmd[2][0] == 'q' }, { "isReply", false }, { "ReplyId", 0 } }.ToString().Replace("\n", ""));
                                break;
                            case "read":
                                if (File.Exists("file")) Console.WriteLine(File.ReadAllText("file"));
                                break;
                            case "lsave":
                                File.WriteAllText("user", cmd[1] + "\n" + cmd[2]);
                                break;
                            case "lauto":
                                webSocket.Send("Login\n" + File.ReadAllText("user") + "\n\n");
                                break;
                            case "write":
                                File.WriteAllText("file", cmd[1]);
                                break;
                            default:
                                break;
                        }
                    }
                }
                catch(Exception e)
                {
                    Console.WriteLine(e);
                }
            }
#if false
            Console.WriteLine("Login/Register");
        Start: string cmd = Console.ReadLine();
            try
            {
                if (cmd.ToLower() == "login")
                {

                }
                else if (cmd.ToLower() == "register")
                {
                    Console.WriteLine("Email address:");
                    cmd = Console.ReadLine();
                    WebSocket webSocket = Client.GetEmail(cmd, host);
                    Console.WriteLine("username")
                }
                else goto Start;
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
                goto Start;
            }
#endif
        }
        static void send(string s)
        {
            webSocket.Send(s);
        }
        static string crm(string msg,long target,bool isGroup,bool isReply=false,long replyId = 0)
        {
            return new JObject { { "msg", msg }, { "target", target }, { "isGroup", isGroup }, { "isReply", isReply }, { "ReplyId", replyId } }.ToString();
        }
    }
}
/*
 * 
 * 
 * {
 * "derivation": 语出
 * , "example": "但也有少数意志薄弱的……逐步上当，终至堕入～。★《上饶集中营·炼狱杂记》"
 * , "explanation": "阿鼻梵语的译音，意译为无间”，即痛苦无有间断之意。常用来比喻黑暗的社会和严酷的牢狱。又比喻无法摆脱的极其痛苦的境地。", "pinyin": "ā bí dì yù", "word": "阿鼻地狱", "abbreviation": "abdy"}
 */